using AlibabaCloud.SDK.Dypnsapi20170525.Models;
using AlibabaCloud.TeaUtil;
using Tea;
using Vin.Extension.Alibaba.Options;
using Vin.Extension.Alibaba.Tools;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.AssertCategory;
using Vin.Tool.Domain.ExceptionModel;

namespace Vin.Extension.Alibaba.Services;

public class DypnsService : AlibabaBaseService<AlibabaCloud.SDK.Dypnsapi20170525.Client>
{
    public DypnsOption DypnsOption => VinApp.GetOption<DypnsOption>();

    public override string Endpoint => DypnsOption.Endpoint ?? "dypnsapi.aliyuncs.com";

    /// <summary>
    /// 获取手机号码
    /// </summary>
    /// <param name="token">App 端 SDK 获取的登录 Token。</param>
    /// <param name="outId">外部流水号。</param>
    /// <returns></returns>
    public async Task<string> GetMobileAsync(string token, string? outId = null)
    {
        if (string.IsNullOrWhiteSpace(token))
            throw new ArgumentNullException(nameof(token), "Token cannot be null or empty.");
        var request = new GetMobileRequest()
        {
            AccessToken = token,
            OutId = outId
        };
        try
        {
            var response = await AccessClient.GetMobileAsync(request);
            if (!AlibabaTool.IsSuccess(response.Body.Code)) throw new BusinessException(response.Body.Message);
            if (response.Body.GetMobileResultDTO.Mobile.IsNullOrEmpty())
                throw new BusinessException("获取手机号码失败，请检查 Token 是否有效或是否有权限。");
            return response.Body.GetMobileResultDTO.Mobile;
        }
        catch (TeaException e)
        {
            throw new BusinessException($"获取手机号码失败: {e.Message}");
        }
        catch (Exception e)
        {
            throw;
        }
    }
}